﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;

namespace libvkontakte
{
    internal class Connection
    {
        private readonly CookieContainer _cookieJar;
        public WebProxy Proxy = null;

        public Connection()
        {
            this._cookieJar = new CookieContainer();
        }

        public Connection(WebProxy webProxy)
        {
            this._cookieJar = new CookieContainer();
            this.Proxy = webProxy;
        }

        /// <summary>
        /// Отправка запроса на указанный url. Возможны входные данные.
        /// </summary>
        /// <param name="url"></param>
        /// <param name="data"></param>
        /// <returns>HttpWebResponse объект</returns>
        public HttpWebResponse SendRequest(string url, string data = null)
        {
            var request = HttpWebRequest.Create(url) as HttpWebRequest;
            request.CookieContainer = this._cookieJar;

            if (Proxy != null)
                request.Proxy = Proxy;

            if(data != null)
            {
                var encoding = new ASCIIEncoding();
                byte[] encodedData = encoding.GetBytes(data);

                request.Method = "POST";
                request.ContentType = "application/x-www-form-urlencoded";
                request.ContentLength = encodedData.Length;
                
                Stream reqStream = request.GetRequestStream();
                reqStream.Write(encodedData,0,encodedData.Length);
                reqStream.Close();
                
            }
            HttpWebResponse response = null;
            response = request.GetResponse() as HttpWebResponse;
            return response;
           
        }

        /// <summary>
        /// Получает строку, с содержимым страницы по заданному запросу.
        /// </summary>
        /// <param name="response">HttpWebResponse объект из которого загружается страница.</param>
        /// <returns>Возвращает строку с содержимым страницы</returns>
        public static string ReadResponse(HttpWebResponse response)
        {
            byte[] buffer = new byte[8192];
            var sb = new StringBuilder();

            Stream str = response.GetResponseStream();
            int count = 0;

            var encoding = Encoding.GetEncoding(1251);

            do
            {
                count = str.Read(buffer, 0, buffer.Length);

                if (count != 0)
                {
                    //tempString = encoding.GetString(buffer, 0, count);
                    string tempString = Encoding.UTF8.GetString(buffer, 0, count);
                    sb.Append(tempString);
                }
            } while (count > 0);

            return sb.ToString();
        }

    }

}
